package com.milk.Dao;

import com.milk.DB.DBConnection;
import com.milk.entity.Employees;

import java.sql.*;

public class EmployeesDao {

    public static Employees findByUsernameAndPassword(String username, String password) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Employees employee = null;

        try {
            // 获取数据库连接
            conn = DBConnection.getConnection();

            // SQL 查询语句
            String sql = "SELECT * FROM employees WHERE username = ? AND password = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);

            // 执行查询
            rs = pstmt.executeQuery();

            // 如果查询结果不为空，返回 Employees 对象
            if (rs.next()) {
                employee = new Employees();
                employee.setId(rs.getInt("id")); // 设置员工 ID
                employee.setUsername(rs.getString("username")); // 设置用户名
                employee.setPassword(rs.getString("password")); // 设置密码
                // 其他字段的设置（如果有其他字段，可以继续添加）
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库资源
            closeResources(rs, pstmt, conn);
        }

        return employee;
    }
    // 添加注册新员工的方法
    public static int registerEmployee(String username, String password) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = 0;

        try {
            // 获取数据库连接
            conn = DBConnection.getConnection();

            // SQL 插入语句
            String sql = "INSERT INTO employees (username, password) VALUES (?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);

            // 执行插入
            result = pstmt.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库资源
            closeResources(null, pstmt, conn);
        }

        return result;
    }
    // 关闭数据库资源的方法
    private static void closeResources(ResultSet rs, Statement stmt, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}